package com.nantong.admin.config;

import java.io.IOException;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * CORS过滤器，优先级高于Sa-Token拦截器
 * 确保跨域请求被正确处理，避免Sa-Token上下文初始化问题
 */
@Component
@Order(Ordered.HIGHEST_PRECEDENCE) // 确保最高优先级
public class CorsFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化时不需要特殊处理
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 允许的请求来源
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        // 允许的请求方法
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        // 允许的请求头
        response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type, X-Requested-With, token");
        // 允许暴露的响应头
        response.setHeader("Access-Control-Expose-Headers", "Authorization");
        // 允许携带认证信息
        response.setHeader("Access-Control-Allow-Credentials", "true");
        // 预检请求的有效期，单位是秒
        response.setHeader("Access-Control-Max-Age", "3600");

        // 对于OPTIONS请求直接放行，不再执行后续的过滤器
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return;
        }

        // 继续执行过滤器链
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        // 销毁时不需要特殊处理
    }
}
